package org.streets.context.internal;

import java.lang.reflect.Method;

import org.streets.commons.util.StringUtils;
import org.streets.annotations.Detail;
import org.streets.annotations.Portal;
import org.streets.context.definition.FunctionDefinition;
import org.streets.context.definition.ModuleDefinition;

/**
 * 模块功能定义
 * @author dzb
 *
 */
public class FunctionDefinitionImpl implements FunctionDefinition {	
	//
	protected String id;
	//
	protected String name;
	//
	protected String hint;
	//
	protected String memo; 
	
	protected String roles; 
	
	protected String portal;
	
	protected ModuleDefinition module;
	
	protected String icon;
	
	protected int index;
	
	FunctionDefinitionImpl(ModuleDefinition module, Method method) {
		
		Detail detail = method.getAnnotation(Detail.class);
		this.module = module;
		if (StringUtils.isBlank(detail.id()))
			this.id = module.getId()+"."+resolveId(method);
		else
			this.id = module.getId()+"."+detail.id();
		
		this.icon = detail.icon();
		this.name = detail.name();
		this.hint = detail.hint();
		this.index = detail.index();
		
		Portal pt = method.getAnnotation(Portal.class);
		if (pt != null) {
			this.portal = pt.value();
		}
	}
	/**
	 * convert java method name to function id
	 * example: getRemoteCaclTax -> get_remote_calc_tax
	 * @param method
	 * @return
	 */
	private String resolveId(Method method) {
		StringBuilder attr_name = new StringBuilder();
		String method_name = method.getName();
		int pos = 0;
		for (int i=0; i<method_name.length(); i++) {
			if (Character.isUpperCase(method_name.charAt(i))) {
				attr_name.append(StringUtils.uncapitalize(method_name.substring(pos, i)));
				attr_name.append('_');
				pos = i;
			}
		}
		return attr_name.append(method_name.substring(pos)).toString().toLowerCase();
	}
		
	public String getId() {

		return id;
	}

	public String getName() {

		return name;
	}
	
	public String getHint() {

		return hint;
	}

	public String getMemo() {

		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public String getRoles() {
		return roles;
	}

	public void setRoles(String roles) {
		this.roles = roles;
	}
	
	public String getPortal() {
		return portal;
	}

	public ModuleDefinition getModule(){
		return module;
	}
	
	public String getIcon() {
		return icon;
	}
	
	public int getIndex() {
		return index;
	}
}
